from celery.result import AsyncResult
from core import Logger
from core.tasks.app import download
from core.models.api import APICode, APIResult
from fastapi import HTTPException, status, APIRouter
import asyncio
import base64

router = APIRouter()
@router.get("/download")
async def download_url(url: str):
    """
    异步下载给定URL的内容。

    参数:
    url: str - 需要下载内容的URL地址。

    返回值:
    如果下载成功，返回一个包含下载内容的APIResult对象；如果下载失败，抛出HTTPException异常。
    """
    try:
        task: AsyncResult = download.delay(url)  # 创建一个异步任务来执行下载
    except Exception as e:
        # 如果创建任务失败，抛出HTTP异常
        Logger.error(f"Failed to create task: {e}")
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="下载任务创建失败")
    
    while not task.ready():  # 等待任务完成
        await asyncio.sleep(0.5)  # 每0.5秒检查一次任务状态

    # 获取任务的结果
    try:
        result: str = task.get()
    except Exception as e:
        # 如果获取结果失败，抛出HTTP异常
        Logger.error(f"Failed to get task result: {e}")
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="获取下载结果失败")
    
    data = base64.b64encode(result.encode("utf-8"))  # 对结果进行base64编码

    # 根据任务结果返回响应
    if result:  
        return APIResult(code=APICode.Success, msg="ok", data={"content":data})  # 下载成功，返回结果
    else:  
        # 下载失败，抛出HTTP异常
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="下载失败, 返回结果为空")
